package com.night.icm.controller.token;

import com.night.icm.common.jwt.JwtTokenUtil;
import com.night.icm.persistence.core.entity.JwtToken;
import com.night.icm.persistence.core.entity.JwtUser;
import com.night.icm.persistence.core.entity.LoginUser;
import com.night.icm.persistence.core.entity.User;
import com.night.icm.persistence.core.repository.UserRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Collection;

/**
 * TokenController
 *
 * @author Liao ZhiYong
 * @date 2019/12/9
 */
@Api(tags = {"令牌管理"})
@RestController
@RequestMapping("/api/token")
public class TokenController {

    private final AuthenticationManager authenticationManager;
    private final UserRepository userRepository;
    @Autowired
    public TokenController(AuthenticationManager authenticationManager, UserRepository userRepository) {
        this.authenticationManager = authenticationManager;
        this.userRepository = userRepository;
    }

    @ApiOperation(value = "使用用户账号和密码生成访问令牌")
    @PostMapping("")
    public JwtToken generationToken(@ApiParam(value = "登录信息", required = true) @RequestBody @Validated LoginUser loginInfo, HttpServletRequest request) {
        UsernamePasswordAuthenticationToken principal = new UsernamePasswordAuthenticationToken(loginInfo.getUsername(), loginInfo.getPassword());
        principal.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        Authentication authentication = authenticationManager.authenticate(principal);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        JwtUser jwtUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String role = "";
        Collection<? extends GrantedAuthority> authorities = jwtUser.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            role = authority.getAuthority();
        }
        boolean isRemember = loginInfo.getRememberMe() == 1;
        String token = JwtTokenUtil.createToken(jwtUser.getUsername(), role, isRemember);
        return createToken(jwtUser.getUsername(), role, token);
    }

    /**
     * 组装 Jwttoken
     *
     * @param userName 用户名
     * @param role     用户角色
     * @param token    token
     * @return Jwttoken
     */
    private JwtToken createToken(String userName, String role, String token) {
        User user = this.userRepository.findByUsername(userName);
        JwtToken jwtToken = new JwtToken();
        jwtToken.setUserId(user.getId().toString());
        jwtToken.setUserName(userName);
        jwtToken.setUserRole(role);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        jwtToken.setIssued(dateFormat.format(JwtTokenUtil.getIssueDateFromToken(token)));
        jwtToken.setExpires(dateFormat.format(JwtTokenUtil.getExpirationDateFormToken(token)));
        jwtToken.setToken(token);
        return jwtToken;
    }

}